/*
* @Author: Marte
* @Date:   2017-04-13 11:02:13
* @Last Modified by:   Marte
* @Last Modified time: 2017-05-04 10:56:08
*/

export default {
    install(Vue) {
        Vue.prototype.getHttp = function (url1, param) {
            return
            this.$http({
                method: 'GET',
                url: 'http://192.168.10.124:8080/oauth' + url1,
                data: param,
                headers: { "X-Requested-With": "XMLHttpRequest" },
                emulateJSON: true
            });
        }
        /*调用接口的公共方法*/
        Vue.prototype.postHttp = function (url, param) {
            // var head_token = localStorage.getItem("token");
            // Vue.http.headers.common['token']=head_token;
            return Vue.http.post('../proxy/oauth' + url, param);
        }
        // /*调用接口的公共方法    此方法必须非登录时使用*/
        // Vue.prototype.postHttpB = function(url, param) {
        //   var head_token = localStorage.getItem("token");
        //   Vue.http.headers.common['token']=head_token;
        //   return Vue.http.post('http://192.168.10.124:8080' + url, param);
        // }
        /*调用接口的公共方法    此方法必须非登录时使用*/
        Vue.prototype.postHttpC = function (url, param) {
            var User_Key = localStorage.getItem("UserKey");
            Vue.http.headers.common['UserKey'] = User_Key;
            return Vue.http.post('../proxy' + url, param);
        }
        /*调用接口的公共方法    此方法必须非登录时使用  GET*/
        Vue.prototype.getHttpC = function (url, param) {
            var User_Key = localStorage.getItem("UserKey");
            Vue.http.headers.common['UserKey'] = User_Key;
            return Vue.http.get('../proxy' + url, param);
        }
        //获取url中的参数
        Vue.prototype.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg); //匹配目标参数
            if (r != null) return unescape(r[2]);
            return null; //返回参数值
        }
        //获取url中的参数
        Vue.prototype.getUrlStrParam = function (str, name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = str.match(reg); //匹配目标参数
            if (r != null) return unescape(r[2]);
            return null; //返回参数值
        }
        //登录状态的心跳连接
        Vue.prototype.keeyLive = function (startTime) {
            setTimeout(function () {
                let User_Key = localStorage.getItem("UserKey");
                this.postHttpC("/oauth/changeUserKey?v=1_13", Json.stringify({ "UserKey": User_Key }))
                    .then(response => {
                        let data = response.body;
                        //console.log(data);
                        if (data.Code === "0") {
                            localStorage.setItem("UserKey", UserKey);
                            setCookie("jawasoft_userkey", UserKey, 's' + 90 * 60);
                        } else {
                            console.log(data.Msg);
                            console.log(data.code);
                        }
                    }, (error) => {
                        console.log(error)
                    });
            }, 90 * 60 * 1000
            );
        }
        Vue.prototype.getCookie = function (name) {
            let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        }
        //这是有设定过期时间的使用示例：
        //s20是代表20秒
        //h是指小时，如12小时则是：h12
        //d是天数，30天则：d30
        Vue.prototype.setCookie = function (name, value, time) {

            let formatTime = function (time) {
                let str1 = str.substring(1, str.length) * 1;
                let str2 = str.substring(0, 1);
                if (str2 == "s") {
                    return str1 * 1000;
                }
                else if (str2 == "h") {
                    return str1 * 60 * 60 * 1000;
                }
                else if (str2 == "d") {
                    return str1 * 24 * 60 * 60 * 1000;
                }
            }

            let exp = new Date();
            exp.setTime(exp.getTime() + formatTime(time));
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
        }

        Vue.prototype.removeCookie = function () {
            let exp = new Date();
            exp.setTime(exp.getTime() - 1);
            let cval = getCookie(name);
            if (cval != null)
                document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }



        Vue.prototype.copyProperty = function (obj, sourcePropertyName, newPropertyName, overWrite) {

            let originalSourcePropertyName = sourcePropertyName;
            let originaNewPropertyName = newPropertyName;

            let recursiveCopy = function (obj,
                sourcePropertyName,
                newPropertyName,
                overWrite
            ) {

                if (obj instanceof Array || Object.prototype.toString.call(obj) === "[object Array]") {
                    for (var k in obj)
                        recursiveCopy(obj[k], sourcePropertyName, newPropertyName, overWrite);
                }
                else if (typeof obj === 'object') {
                    if (sourcePropertyName instanceof Array || Object.prototype.toString.call(sourcePropertyName) === "[object Array]") {
                        for (var i in sourcePropertyName) {
                            recursiveCopy(obj, sourcePropertyName[i], newPropertyName[i], overWrite);
                        }
                    }
                    else if (typeof sourcePropertyName === 'string') {
                        if ((obj[newPropertyName] && overWrite) || (!obj[newPropertyName])) {
                            if (typeof obj[sourcePropertyName] == 'object' && obj[sourcePropertyName]) recursiveCopy(obj[sourcePropertyName], originalSourcePropertyName, originaNewPropertyName, overWrite);

                            obj[newPropertyName] = obj[sourcePropertyName];


                        }
                    }
                }
                return obj;

            };

            return recursiveCopy(obj, sourcePropertyName, newPropertyName, overWrite, sourcePropertyName, newPropertyName);


        }
        /**
         * 格式化时间显示方式
         * 用法:format="yyyy-MM-dd hh:mm:ss";
         **/
        Vue.prototype.formatDate = function (v, format) {
            if (!v) return "";
            var d = v;
            if (typeof v === 'string') {
                if (v.indexOf("/Date(") > -1)
                    d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
                else
                    d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0]));//.split(".")[0] 用来处理出现毫秒的情况，截取掉.xxx，否则会出错
            }
            var o = {
                "M+": d.getMonth() + 1,  //month
                "d+": d.getDate(),       //day
                "h+": d.getHours(),      //hour
                "m+": d.getMinutes(),    //minute
                "s+": d.getSeconds(),    //second
                "q+": Math.floor((d.getMonth() + 3) / 3),  //quarter
                "S": d.getMilliseconds() //millisecond
            };
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return format;
        }
        /**
         * json格式转树状结构
         * @param a  {json}      json数据
         * @param  idstr {String}    id的字符串
         * @param  oidstr {String}    父id的字符串
         * @param  childrenStr {String}    children的字符串
         * @return  {Array}     数组
        **/
        Vue.prototype.toTreeData = function (a, idStr, pidStr, childrenStr) {
            var r = [], hash = {}, len = (a || []).length;
            for (var i = 0; i < len; i++) {
                hash[a[i][idStr]] = a[i];
            }
            for (var j = 0; j < len; j++) {
                var aVal = a[j], hashVP = hash[aVal[pidStr]];
                if (hashVP) {
                    !hashVP[childrenStr] && (hashVP[childrenStr] = []);
                    hashVP[childrenStr].push(aVal);
                } else {
                    r.push(aVal);
                }
            }
            return r;
        };

    }
}





